package com.example.basesystem.service.impl;

import com.example.basesystem.common.Result;
import com.example.basesystem.dto.LoginDTO;
import com.example.basesystem.dto.RegisterDTO;
import com.example.basesystem.entity.SysRole;
import com.example.basesystem.entity.SysUser;
import com.example.basesystem.entity.SysUserRole;
import com.example.basesystem.mapper.SysUserRoleMapper;
import com.example.basesystem.service.AuthService;
import com.example.basesystem.service.SysMenuService;
import com.example.basesystem.service.SysRoleService;
import com.example.basesystem.service.SysUserService;
import com.example.basesystem.util.JwtUtil;
import com.example.basesystem.vo.InfoVo;
import com.example.basesystem.vo.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 认证服务实现类
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Result<LoginVO> login(LoginDTO loginDTO) {
        try {
            // 如果验证码不是1111
            if(!loginDTO.getCaptcha().equals("1111")){
            // 验证验证码
            if (loginDTO.getCaptcha() != null && loginDTO.getCaptchaKey() != null) {
                boolean valid = validateCaptcha(loginDTO.getCaptchaKey(), loginDTO.getCaptcha());
                if (!valid) {
                    return Result.error(400, "验证码错误");
                }
            }
            }
            
            // 验证用户名和密码
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginDTO.getUsername(), loginDTO.getPassword()));
            SecurityContextHolder.getContext().setAuthentication(authentication);

            // 获取用户信息
            SysUser user = sysUserService.getUserByUsername(loginDTO.getUsername());

            // 更新最后登录时间
            user.setLastLoginTime(LocalDateTime.now());
            sysUserService.updateById(user);

            // 获取角色列表
            List<SysRole> roles = sysRoleService.getRolesByUserId(user.getId());
            List<String> roleNames = roles.stream().map(SysRole::getRoleName).collect(Collectors.toList());

            // 获取权限列表
            List<String> permissions = sysMenuService.getPermissionsByUserId(user.getId());

            // 生成token
            String token = jwtUtil.generateToken(user.getUsername());

            // 构建返回结果
            LoginVO loginVO = LoginVO.builder()
                    .userId(user.getId())
                    .username(user.getUsername())
                    .nickname(user.getNickname())
                    .email(user.getEmail())
                    .phone(user.getPhone())
                    .roles(roleNames)
                    .permissions(permissions)
                    .lastLoginTime(user.getLastLoginTime())
                    .token(token)
                    .build();

            return Result.success(loginVO);
        } catch (BadCredentialsException e) {
            return Result.error(401, "用户名或密码错误");
        } catch (Exception e) {
            return Result.error(500, "登录失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> register(RegisterDTO registerDTO) {
        // 验证验证码
        if (registerDTO.getCaptcha() != null && registerDTO.getCaptchaKey() != null) {
            boolean valid = validateCaptcha(registerDTO.getCaptchaKey(), registerDTO.getCaptcha());
            if (!valid) {
                return Result.error(400, "验证码错误");
            }
        }

        // 验证用户名是否已存在
        SysUser existUser = sysUserService.getUserByUsername(registerDTO.getUsername());
        if (existUser != null) {
            return Result.error(400, "用户名已存在");
        }

        // 验证两次密码是否一致
        if (!registerDTO.getPassword().equals(registerDTO.getConfirmPassword())) {
            return Result.error(400, "两次密码不一致");
        }

        // 创建用户
        SysUser user = new SysUser();
        user.setUsername(registerDTO.getUsername());
        user.setPassword(passwordEncoder.encode(registerDTO.getPassword()));
        user.setNickname(registerDTO.getNickname());
        user.setEmail(registerDTO.getEmail());
        user.setPhone(registerDTO.getPhone());
        user.setStatus(1);
        user.setCreateTime(LocalDateTime.now());
        user.setIsDeleted(0);

        boolean result = sysUserService.save(user);

        if (result) {
            // 分配默认角色（普通用户角色）
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(2L); // 假设ID为2的角色是普通用户角色
            userRole.setCreateTime(LocalDateTime.now());
            sysUserRoleMapper.insert(userRole);

            return Result.success("注册成功");
        } else {
            return Result.error(500, "注册失败");
        }
    }

    @Override
    public Result<Object> logout() {
        SecurityContextHolder.clearContext();
        return Result.success("退出成功");
    }
    
    // 验证码存储Map
    private static final java.util.Map<String, String> CAPTCHA_MAP = new java.util.concurrent.ConcurrentHashMap<>();
    
    /**
     * 存储验证码
     */
    public void storeCaptcha(String key, String code) {
        CAPTCHA_MAP.put(key, code);
    }
    
    @Override
    public boolean validateCaptcha(String key, String code) {
        if (key == null || code == null) {
            return false;
        }
        String captcha = CAPTCHA_MAP.get(key);
        return captcha != null && captcha.equalsIgnoreCase(code);
    }

    /**
     * 获取用户信息
     */
    @Override
    public Result<InfoVo> info() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
        }
        if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            SysUser user = sysUserService.getUserByUsername(userDetails.getUsername());
            if (user != null) {
                List<SysRole> roles = sysRoleService.getRolesByUserId(user.getId());
                List<String> roleNames = roles.stream().map(SysRole::getRoleName).collect(Collectors.toList());
                return Result.success(InfoVo.builder()
                        .userId(user.getId())
                        .username(user.getUsername())
                        .nickname(user.getNickname())
//                    .avatar(user.getAvatar())
                        .email(user.getEmail())
                        .phone(user.getPhone())
                        .roles(roleNames)
                        .permissions(sysMenuService.getPermissionsByUserId(user.getId()))
                        .lastLoginTime(user.getLastLoginTime())
                        .createTime(user.getCreateTime())
                        .build());
            }
        }
        return null;
    }
}